package apis

import (
	"github.com/gin-gonic/gin"
	"app/bt"
	common "app/util"
	"strconv"
	"net"
	"fmt"
)

//https://blog.csdn.net/wangpingfang/article/details/4209559

func CreateReqeust(c *gin.Context) *bt.Request {

	req := new(bt.Request)
	req.Port 		= 	c.Query("port")
	req.IPAddress 	= 	c.ClientIP()
	req.IPKey		=	common.Inet_aton(net.ParseIP(c.ClientIP()))
	req.PeerId 		= 	common.ByteToString(c.Query("peer_id"))
	req.InfoHash 	= 	common.ByteToString(c.Query("info_hash"))
	req.Key 		= 	common.ByteToString(c.Query("key"))
	req.Downloaded,_  = strconv.ParseUint(c.Query("downloaded"), 10, 64)
	req.Uploaded,_  = 	strconv.ParseUint(c.Query("uploaded"), 10, 64)
	req.Left,_  	= 	strconv.ParseUint(c.Query("left"), 10, 64)
	req.NumWant,_ 	= 	strconv.Atoi(c.Query("numwant"))
	req.Event		=	c.DefaultQuery("event",bt.ActiveString)

	return req
}

func Response(hashkey string,resp *bt.Response) {

	resp.Interval = 100
	resp.Mininterval = 100
	resp.TrackerId = "test id"



	btorrent ,err := bt.Engine().Session.GetTorrent(hashkey)
	if err != nil {
		return
	}

	iStart :=  btorrent.StartPeersCount()
	iComplate := btorrent.ComplatePeersCount()

	resp.Incomplete = iStart
	resp.Complete = iStart + iComplate
	resp.Downloaded = iComplate

	fmt.Println("\n")
	fmt.Print(resp.Incomplete,resp.Complete,resp.Downloaded)
	fmt.Println("\n")
}
